package com.zzl.springboot_mybatis_demo.countdownlatch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Description：通过CountDownLatch工具类，模拟高并发
 * Created by 朱正磊 on 2019-09-22 11:47
 */
public class CountDownLatchDemo {

    public void demo() {
        CountDownLatch startGate = new CountDownLatch(1);
        CountDownLatch latch = new CountDownLatch(20);
        Runnable runnable = () -> {
            try {
                startGate.await();
                System.out.println("**************************线程开始**************************");
                Thread.sleep(2000);
                getLock();
                System.out.println("**************************线程结束**************************");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                latch.countDown();
            }
        };

        ExecutorService executorService = Executors.newFixedThreadPool(20);
        for (int i = 0; i < 20; i++) {
            executorService.submit(runnable);
        }

        System.out.println("===============================");

        try {
            startGate.countDown();
            //当所有线程完成后，才继续往下执行，阻塞作用
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        executorService.shutdown();
    }

    public void getLock() {
        System.out.println("发送请求");
    }

    public static void main(String[] args) {
        CountDownLatchDemo demo = new CountDownLatchDemo();
        demo.demo();
    }

}
